package Problem8;

class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.myAtoi("   5"));
    }

    public int myAtoi(String str) {
        long num = 0;
        int len = str.length();
        boolean play = false;
        int tab = 1;
        if (str == "")
            return 0;
        str.trim(); // 去除字符串前面的空格
        if ((str.charAt(0) > '9' || str.charAt(0) < '0') && (str.charAt(0) == '+' || str.charAt(0) == '-'))
            return 0;
        for (int i = 0 ; i < len ; i++){
            if (str.charAt(i) > '9' || str.charAt(i) < '0' ){
                if (!play)
                    continue;
                else
                    break;
            }
            else {
                play = true;
                if (i > 1)
                {
                    if (str.charAt(i-1) == '+' ){
                        tab = 1;
                    }
                    else if (str.charAt(i-1) == '-'){
                        tab = -1;
                    }
                }
                num += str.charAt(i)-'0';
                num *= 10;
            }
        }
        num /= 10;
        num *= tab;
        if (num > Integer.MAX_VALUE ){
            return Integer.MAX_VALUE;
        }else if (num < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }else return (int)num;
    }
}